package com.zimmur.app.mocolink.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zimmur.app.mocolink.dao.GoodsImageMapper;
import com.zimmur.app.mocolink.dao.GoodsItemMapper;
import com.zimmur.app.mocolink.dao.GoodsMapper;
import com.zimmur.app.mocolink.dao.GroupGoodsMapper;
import com.zimmur.app.mocolink.dao.StorageFilesMapper;
import com.zimmur.app.mocolink.domain.apiData.GoodsData;
import com.zimmur.app.mocolink.domain.apiData.PictureData;
import com.zimmur.app.mocolink.domain.apiData.SkuData;
import com.zimmur.app.mocolink.domain.common.Constant;
import com.zimmur.app.mocolink.domain.model.Goods;
import com.zimmur.app.mocolink.domain.model.GoodsImage;
import com.zimmur.app.mocolink.domain.model.GoodsImageExample;
import com.zimmur.app.mocolink.domain.model.GoodsItem;
import com.zimmur.app.mocolink.domain.model.GoodsItemExample;
import com.zimmur.app.mocolink.domain.model.OrderDetail;
import com.zimmur.app.mocolink.domain.model.StorageFiles;
import com.zimmur.app.mocolink.domain.param.GoodsParam;
import com.zimmur.app.mocolink.domain.param.GoodsParamForManage;
import com.zimmur.app.mocolink.domain.util.DateUtils;
import com.zimmur.app.mocolink.domain.util.PageUtil;
import com.zimmur.app.mocolink.domain.util.StringUtils;
import com.zimmur.app.mocolink.domain.vo.GoodsDetailVo;
import com.zimmur.app.mocolink.domain.vo.GoodsForManageInfo;
import com.zimmur.app.mocolink.domain.vo.GoodsForManageVo;
import com.zimmur.app.mocolink.domain.vo.GoodsInfo;
import com.zimmur.app.mocolink.domain.vo.GoodsInfoVo;
import com.zimmur.app.mocolink.domain.vo.GoodsVo;
import com.zimmur.app.mocolink.domain.vo.GroupGoodsInfo;
import com.zimmur.app.mocolink.service.IGoodsService;

@Service
public class GoodsServiceImpl implements IGoodsService{

	@Autowired
	private GoodsMapper goodsMapper;
	@Autowired
	private GoodsItemMapper goodsItemMapper;
	@Autowired 
	private GoodsImageMapper goodsImageMapper;
	@Autowired
	private GroupGoodsMapper groupGoodsMapper;
	@Autowired
	private StorageFilesMapper storageFilesMapper;
	

	@Override
	public Goods selectById(Integer goodsId) {
		return goodsMapper.selectByPrimaryKey(goodsId);
	}

	@Override
	public int update(Goods goods) {
		return goodsMapper.updateByPrimaryKeySelective(goods);
	}
	@Override
	public GoodsForManageVo queryGoodsForManage(GoodsParamForManage param) {
		GoodsForManageVo page  = new GoodsForManageVo();
		int count = goodsMapper.countByGoodsParam(param);
		List<GoodsForManageInfo> goodsItemList = goodsMapper.queryGoodsForManage(param);
		page.setTotalRecord(count);
		page.setPageNo(param.getPageNo());
		page.setPageSize(param.getPageSize());
		page.setGoodsItemList(goodsItemList);
		return page;
	}

	@Override
	public void updateStockQuantity(List<OrderDetail> details,Integer type) {
		switch (type) {
		case Constant.Goods_Stocked_Buy:
			for(OrderDetail detail:details){
				GoodsItem goodsItem = goodsItemMapper.selectByPrimaryKey(detail.getGoodsItemId());
				if(goodsItem!=null){
					int lockedQuantity = detail.getQuantity()+goodsItem.getLockedQuantity();
					goodsItem.setLockedQuantity(lockedQuantity);
					goodsItemMapper.updateByPrimaryKey(goodsItem);
				}
			}
			break;
		case Constant.Goods_Stocked_Pay:
			for(OrderDetail detail:details){
				GoodsItem goodsItem = goodsItemMapper.selectByPrimaryKey(detail.getGoodsItemId());
				if(goodsItem!=null){
					int lockedQuantity = goodsItem.getLockedQuantity()-detail.getQuantity();
					int stockQuantity = goodsItem.getStockedQuantity()-detail.getQuantity();
					goodsItem.setStockedQuantity(stockQuantity);
					goodsItem.setLockedQuantity(lockedQuantity);
					goodsItemMapper.updateByPrimaryKey(goodsItem);
				}
			}
			break;
		case Constant.Goods_Stocked_Cancel:
			for(OrderDetail detail:details){
				GoodsItem goodsItem = goodsItemMapper.selectByPrimaryKey(detail.getGoodsItemId());
				if(goodsItem!=null){
					int lockedQuantity = goodsItem.getLockedQuantity()-detail.getQuantity();
					goodsItem.setLockedQuantity(lockedQuantity);
					goodsItemMapper.updateByPrimaryKey(goodsItem);
				}
			}
			break;

		default:
			break;
		}
	}

	@Override
	public GoodsVo selectGoodsDetail(Integer goodsId,Integer userId) {
		GoodsVo goodsVo;
		GoodsInfo goodsInfo = goodsMapper.selectGoodsInfo(goodsId, userId);
		if(goodsInfo!=null){
			goodsMapper.updateGoodsQuantity(goodsId, 1, null);
			goodsVo = new GoodsVo();
			List<GoodsImage> goodsImages = goodsImageMapper.selectByGoodsId(goodsId);
			goodsInfo.setGoodsImageList(goodsImages);
			goodsVo.setGoodsInfo(goodsInfo);
			List<GroupGoodsInfo> groupGoodsInfos = groupGoodsMapper.selectByGoodsId(goodsId);
			goodsVo.setGroupGoodsList(groupGoodsInfos);
		}else{
			goodsVo=null;
		}
		return goodsVo;
	}

	@Override
	public int changeGoodsStatus(Integer goodsId, String status, String userName) {
		Goods goods = new Goods();
		goods.setId(goodsId);
		goods.setGoodsStatus(status);
		goods.setEatablishUser(userName);
		goods.setEatablishTime(new Date());
		if("sale".equals(status)){
			goods.setPubuser(userName);
			goods.setPubdate(new Date());
		}
		return goodsMapper.updateByPrimaryKeySelective(goods);
	}
	@Transactional
	@Override
	public int saveGoodsDetailForManage(GoodsDetailVo vo, String userName) {
		//1.添加商品信息
		Goods goods = new Goods();
		Date nowTime = DateUtils.getNow();
		goods.setBrandId(vo.getBrandId());
		goods.setCollectionNum(vo.getCollectionNum());
		goods.setContent(vo.getContent());
		goods.setCoverImage(vo.getCoverImage());
		goods.setEatablishTime(nowTime);
		goods.setEatablishUser(userName);
		goods.setGoodsName(vo.getGoodsName());
		goods.setGoodsStatus(vo.getGoodsStatus());
		goods.setIsSp(vo.getIsSp());
		goods.setMaterial(vo.getMaterial());
		goods.setPrice(vo.getPrice());
		goods.setQuarter(vo.getQuarter());
		goods.setSaleNum(vo.getSaleNum());
		goods.setSmallDesc(vo.getSmallDesc());
		goods.setStyleCode(vo.getStyleCode());
		goods.setTags(vo.getTags());
		goods.setTypeId(vo.getTypeId());
		goods.setMinimumQuantity(vo.getMinimumQuantity());
		if(Constant.Goods_Status_Sale.equals(vo.getGoodsStatus())){
			goods.setPubuser(userName);
			goods.setPubdate(nowTime);
		}
		Integer inventoryNum = 0 ;
		//计算商品明细的库存量
		List<GoodsItem> itemList = vo.getItemList();
		if(itemList!=null&&!itemList.isEmpty()){
			for(GoodsItem item:itemList){
				inventoryNum += item.getStockedQuantity();
			}
		}
		goods.setInventoryNum(inventoryNum);
		Integer flag = goodsMapper.insertSelective(goods);
		if(flag==1){
			Integer seq = goods.getId();
			//2.添加商品明细
			if(itemList!=null&&!itemList.isEmpty()){
				for(GoodsItem item:itemList){
					item.setGoodsId(seq);
					flag = goodsItemMapper.insertSelective(item);
				}
			}
			//3.添加图片信息
			if(flag==1){
				List<GoodsImage> imagesList = vo.getImageList();
				if(imagesList!=null&&!imagesList.isEmpty()){
					for(GoodsImage image:imagesList){
						image.setGoodsId(seq);
						flag = goodsImageMapper.insertSelective(image);
					}
				}
			}
		}
		return flag;
	}

	@Override
	public int updateGoodsDetailForManage(GoodsDetailVo vo, String userName) {
		//1.添加商品信息
		Goods goods = new Goods();
		Date nowTime = DateUtils.getNow();
		goods.setId(vo.getId());
		goods.setBrandId(vo.getBrandId());
		goods.setCollectionNum(vo.getCollectionNum());
		goods.setContent(vo.getContent());
		goods.setCoverImage(vo.getCoverImage());
		goods.setEatablishTime(nowTime);
		goods.setEatablishUser(userName);
		goods.setGoodsName(vo.getGoodsName());
		goods.setGoodsStatus(vo.getGoodsStatus());
		goods.setIsSp(vo.getIsSp());
		goods.setMaterial(vo.getMaterial());
		goods.setPrice(vo.getPrice());
		goods.setQuarter(vo.getQuarter());
		goods.setSaleNum(vo.getSaleNum());
		goods.setSmallDesc(vo.getSmallDesc());
		goods.setStyleCode(vo.getStyleCode());
		goods.setTags(vo.getTags());
		goods.setTypeId(vo.getTypeId());
		goods.setMinimumQuantity(vo.getMinimumQuantity());
		if(Constant.Goods_Status_Sale.equals(vo.getGoodsStatus())){
			goods.setPubuser(userName);
			goods.setPubdate(nowTime);
		}
		Integer inventoryNum = 0 ;
		//计算商品明细的库存量
		List<GoodsItem> itemList = vo.getItemList();
		if(itemList!=null&&!itemList.isEmpty()){
			for(GoodsItem item:itemList){
				inventoryNum += item.getStockedQuantity();
			}
		}
		goods.setInventoryNum(inventoryNum);
		Integer flag = goodsMapper.updateByPrimaryKeySelective(goods);
		if(flag==1){
			//2.变更商品明细
			if(itemList!=null&&!itemList.isEmpty()){
				//2.1.删除原有的商品明细
				GoodsItemExample ex =  new GoodsItemExample();
				ex.createCriteria().andGoodsIdEqualTo(vo.getId());
				int count = goodsItemMapper.countByExample(ex);
				if(count>0){
					goodsItemMapper.deleteByExample(ex);
				}
				//2.2.新增商品明细
				for(GoodsItem item:itemList){
					item.setGoodsId(vo.getId());
					flag = goodsItemMapper.insertSelective(item);
				}
			}
			//3.变更图片信息
			if(flag==1){
				//3.1.先删除原有的图片信息
				GoodsImageExample  ex = new GoodsImageExample();
				ex.createCriteria().andGoodsIdEqualTo(vo.getId());
				List<GoodsImage> imageList =  goodsImageMapper.selectByExample(ex);
				if(imageList!=null&!imageList.isEmpty()){
					goodsImageMapper.deleteByExample(ex);
				}
				//3.2新增变更后的图片信息
				List<GoodsImage> imagesList = vo.getImageList();
				if(imagesList!=null&&!imagesList.isEmpty()){
					for(GoodsImage image:imagesList){
						image.setGoodsId(vo.getId());
						flag = goodsImageMapper.insertSelective(image);
					}
				}
			}
		}
		return flag;
	}
	@Override
	public PageUtil<GoodsInfo> queryGoodsByParam(GoodsParam goodsParam) {
		PageUtil<GoodsInfo> page = new PageUtil<>();
		List<GoodsInfo> list = goodsMapper.selectGoodsInfoByParam(goodsParam);
		Integer count = goodsMapper.countGoodsInfoByParam(goodsParam);
		page.setPageNo(goodsParam.getPageNo());
		page.setPageSize(goodsParam.getPageSize());
		page.setItemList(list);
		page.setTotalRecord(count);
		return page;
	}

	@Override
	public PageUtil<GoodsForManageInfo> queryGoodsByParam(GoodsParamForManage param) {
		PageUtil<GoodsForManageInfo> page  = new PageUtil<>();
		int count = goodsMapper.countByGoodsParam(param);
		List<GoodsForManageInfo> goodsItemList = goodsMapper.queryGoodsForManage(param);
		page.setPageNo(param.getPageNo());
		page.setPageSize(param.getPageSize());
		page.setTotalRecord(count);
		page.setItemList(goodsItemList);
		return page;
	}

	@Override
	public GoodsInfoVo queryGoodsInfo(Integer goodsId) {
		GoodsInfoVo vo = new GoodsInfoVo();
		//1.查询商品信息
		Goods goods = goodsMapper.selectByPrimaryKey(goodsId);
		vo.setGoods(goods);
		//2.查询商品明细
		GoodsItemExample example = new GoodsItemExample();
		example.createCriteria().andGoodsIdEqualTo(goodsId);
		List<GoodsItem> itemList = goodsItemMapper.selectByExample(example);
		vo.setItemList(itemList);
		//3.查询图片信息
		GoodsImageExample ex = new GoodsImageExample();
		ex.createCriteria().andGoodsIdEqualTo(goodsId);
		List<GoodsImage> imageList= goodsImageMapper.selectByExample(ex);
		vo.setImageList(imageList);
		return vo;
	}

	@Override
	public int savePushData(List<GoodsData> datas) {
		if(datas==null || datas.size()==0){
			return 1;
		}
		for(GoodsData goodsData:datas){
			Goods goods = goodsMapper.selectByPushId(goodsData.getId());
			if(goods!=null){
				Integer goodsId=goods.getId();
				String group=goodsData.getPicGroup();
				String covImage=goodsData.getCoverPicture();
				if(!StringUtils.isBlank(covImage,group)){
					String coverImage=goods.getCoverImage();
					if(!StringUtils.isBlank(coverImage)){
						StorageFiles files=storageFilesMapper.selectByPrimaryKey(Integer.valueOf(coverImage));
						files.setStorageGroup(group);
						files.setStorageId(covImage);
						storageFilesMapper.updateByPrimaryKeySelective(files);
					}else{
						StorageFiles files = new StorageFiles();
						files.setCreateTime(DateUtils.getNow());
						files.setCreator("back");
						files.setStorageGroup(group);
						files.setStorageId(covImage);
						String ext = covImage.substring(covImage.lastIndexOf(".")+1);
						files.setExt(ext);
						files.setType("image");
						if(storageFilesMapper.insertSelective(files)>0){
							int fileId=files.getId();
							goods.setCoverImage(fileId+"");
						}
					}
				}
				goods.setCostPrice(goodsData.getCostPrice());
				goods.setCurrentPrice(goodsData.getCurrentPrice());
				goods.setDistrSupplyPrice(goodsData.getDistrSupplyPrice());
				
				List<SkuData> skuList = goodsData.getSkus();
				int inventoryNum=0;
				if(skuList!=null && skuList.size()>0){
					for(SkuData sku:skuList){
						GoodsItem goodsItem = goodsItemMapper.selectBySku(goodsId, sku.getSku());
						if(goodsItem!=null){
							goodsItem.setStockedQuantity(sku.getAvailableQuantity());
							goodsItemMapper.updateByPrimaryKeySelective(goodsItem);
						}else{
							goodsItem=new GoodsItem();
							goodsItem.setColorCode(sku.getColorCode());
							goodsItem.setColorName(sku.getColorName());
							goodsItem.setSizeCode(sku.getSizeNumber());
							goodsItem.setSizeName(sku.getSizeName());
							goodsItem.setSku(sku.getSku());
							goodsItem.setLockedQuantity(0);
							goodsItem.setStockedQuantity(sku.getAvailableQuantity());
							goodsItem.setGoodsId(goodsId);
							goodsItemMapper.insertSelective(goodsItem);
						}
						inventoryNum+=sku.getAvailableQuantity();
					}
				}
				goods.setInventoryNum(inventoryNum);
				goodsMapper.updateByPrimaryKeySelective(goods);
				List<PictureData> pictureDatas = goodsData.getPicture();
				savePicture(goodsId,pictureDatas);
			}else{
				goods = new Goods();
				goods.setContent(goodsData.getDescription());
				goods.setGoodsName(goodsData.getProductName());
				goods.setGoodsStatus(Constant.Goods_Status_Push);
				goods.setMaterial(goodsData.getIngredients());
				//设置价格
				goods.setCostPrice(goodsData.getCostPrice());
				goods.setCurrentPrice(goodsData.getCurrentPrice());
				goods.setDistrSupplyPrice(goodsData.getDistrSupplyPrice());
				goods.setPrice(new BigDecimal(0));
				goods.setTypeId(0);
				goods.setPushId(goodsData.getId());
				goods.setStyleCode(goodsData.getStyleNo());
				goods.setQuarter(goodsData.getQuarter());
				Integer inventoryNum=0;
				List<SkuData> skuList = goodsData.getSkus();
				List<GoodsItem> goodsItems = new ArrayList<>();
				if(skuList!=null && skuList.size()>0){
					for(SkuData sku:skuList){
						GoodsItem goodsItem = new GoodsItem();
						goodsItem.setColorCode(sku.getColorCode());
						goodsItem.setColorName(sku.getColorName());
						goodsItem.setSizeCode(sku.getSizeNumber());
						goodsItem.setSizeName(sku.getSizeName());
						goodsItem.setSku(sku.getSku());
						goodsItem.setLockedQuantity(0);
						goodsItem.setStockedQuantity(sku.getAvailableQuantity());
						inventoryNum+=sku.getAvailableQuantity();
						goodsItems.add(goodsItem);
					}
				}
				goods.setInventoryNum(inventoryNum);
				String group=goodsData.getPicGroup();
				String covImage=goodsData.getCoverPicture();
				if(!StringUtils.isBlank(covImage,group)){
					StorageFiles files = new StorageFiles();
					files.setCreateTime(DateUtils.getNow());
					files.setCreator("back");
					files.setStorageGroup(group);
					files.setStorageId(covImage);
					String ext = covImage.substring(covImage.lastIndexOf(".")+1);
					files.setExt(ext);
					files.setType("image");
					if(storageFilesMapper.insertSelective(files)>0){
						int fileId=files.getId();
						goods.setCoverImage(fileId+"");
					}
				}
				
				if(goodsMapper.insertSelective(goods)>0){
					int goodsId = goods.getId();
					if(goodsItems.size()>0){
						for(GoodsItem item:goodsItems){
							item.setGoodsId(goodsId);
							goodsItemMapper.insertSelective(item);
						}
					}
					List<PictureData> pictureDatas = goodsData.getPicture();
					savePicture(goodsId,pictureDatas);
				}
			}
		}
		return 1;
	}

	private void savePicture(Integer goodsId,List<PictureData> pictureDatas){
		if(pictureDatas!=null && pictureDatas.size()>0){
			goodsImageMapper.deleteByGoodsId(goodsId);
			for(PictureData picture:pictureDatas){
				StorageFiles files = new StorageFiles();
				String storageId=picture.getSystemName();
				files.setCreateTime(DateUtils.getNow());
				files.setCreator("back");
				files.setStorageGroup(picture.getPicGroup());
				files.setStorageId(storageId);
				files.setOriginalFileName(picture.getOriginName());
				String ext = storageId.substring(storageId.lastIndexOf(".")+1);
				files.setExt(ext);
				files.setType("image");
				if(storageFilesMapper.insertSelective(files)>0){
					int fileId=files.getId();
					GoodsImage goodsImage = new GoodsImage();
					goodsImage.setGoodsId(goodsId);
					goodsImage.setImageUrl(fileId+"");
					goodsImageMapper.insertSelective(goodsImage);
				}
			}
		}
	}
	public static void main(String[] args) {
		String a= "asdasdasda..jpg";
		String ext = a.substring(a.lastIndexOf('.')+1);
		System.out.println(ext);
	}
}
